/****************
 *@description: 
 *@author: Xhd
 *@API: 
 *@date: 2023-12-13 09:50:53
 *@version: V1.0.0
*************************************************************************/

import React, { useEffect, useState, useRef } from 'react';
import GoBack from "@/components/TheGoBack";
import TheButton from "@/components/TheButton";
import { ProFormDateRangePicker, ProTable } from '@ant-design/pro-components';
import { useLocation } from 'react-router-dom';
import { apiGetCouponInfoView, apiGetExchangeInfoPage, apiGetExchangeInfoList } from "@/api/couponManagement/index.js";
import { Decimal } from 'decimal.js';

const CDKList = () => {
  const actionRef = useRef()
  const actionRef_CDK = useRef()
  const location = useLocation()
  const title = "CDK列表"
  const couponId = location.state.couponId
  const [total, setTotal] = useState(0)
  const columns_coupon = [
    {
      title: "优惠券名称",
      dataIndex: "couponTitle",
      key: "couponTitle",
    },
    {
      title: "优惠券类型",
      dataIndex: "couponType",
      key: "couponType",
      valueEnum: {
        'J': { text: '代金券' },
        'Z': { text: '折扣券' },
        'D': { text: '打车券' },
      },
    },
    {
      title: "面值",
      dataIndex: "couponPrice",
      key: "couponPrice",
      render: (text, record) => {
        if (record.couponType === 'J' || record.couponType === 'D') {
          return Decimal(record.couponPrice).div(Decimal(100)).toNumber().toFixed(2)
        }
        if (record.couponType === 'Z') {
          return `${Decimal(record.couponPrice).div(Decimal(10)).toNumber().toFixed(2)}折`
        }
      }
    },
    {
      title: "有效期",
      dataIndex: "effectiveTime",
      key: "effectiveTime",
      render: (text, record) => {
        if (record.timeType === 1 || record.timeType === 2) {
          return <div>{record.effectiveTime}天</div>
        }
        return <div>{`${record.startTime}`} 至 {`${record.endTime}`}</div>
      }
    },
    {
      title: "优惠券状态",
      dataIndex: "couponStatus",
      key: "couponStatus",
      valueEnum: {
        'Y': { text: '启用' },
        'N': { text: '禁用' },
      },
    },
    {
      title: "领取数量",
      dataIndex: "receiveCount",
      key: "receiveCount",
    },
    {
      title: "使用数量",
      dataIndex: "useCount",
      key: "useCount",
    },
  ]
  const columns_CDK = [
    {
      title: "CDK",
      dataIndex: "cdkey",
      key: "cdkey",
    },
    {
      title: "领取用户",
      dataIndex: "nickName",
      key: "nickName",
    },
    {
      title: "兑换时间",
      dataIndex: "exchangeDate",
      key: "exchangeDate",
    },
    {
      title: "使用时间",
      dataIndex: "verificationTime",
      key: "verificationTime",
    },
  ]

  const exportExcel = async () => {
    await apiGetExchangeInfoList({ exchangeValue: couponId, exchangeType: 0 }).then(res => {
      let data = []
      res.data.forEach(item => {
        data.push({
          cdkey: item.cdkey ? item.cdkey : '/',
          nickName: item.nickName ? item.nickName : '/',
          exchangeDate: item.exchangeDate ? item.exchangeDate : '/',
          verificationTime: item.verificationTime ? item.verificationTime : '/',
        })
      })
      const option = {
        fileName: 'CDK列表',
        header: [
          {
            title: 'CDK列表',
            prop: '',
            children: [
              {
                title: 'CDK',
                prop: 'cdkey',
              },
              {
                title: '领取用户',
                prop: 'nickName',
              },
              {
                title: '兑换时间',
                prop: 'exchangeDate',
              },
              {
                title: '使用时间',
                prop: 'verificationTime',
              },
            ]
          },
        ],

        dataSource: data
      }
      Json2Excel(option)
    })
  }

  return (<div className='wrap-box'>
    <GoBack title={title} />
    <div >
      <div style={{ margin: "10px 0", fontSize: 16, fontWeight: 600 }}>优惠券信息</div>
      <ProTable
        actionRef={actionRef}
        scroll={{ x: "max-content", y: '57vh' }}
        bordered={true}
        options={false}
        columns={columns_coupon}
        pagination={false}
        request={async () => {
          // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
          // 如果需要转化参数可以在这里进行修改
          const res = await apiGetCouponInfoView({
            couponId,
          });
          let data = [{ ...res.data }]
          return {
            data,
            // success 请返回 true，
            // 不然 table 会停止解析数据，即使有数据
            success: res.code === 0,
            // 不传会使用 data 的长度，如果是分页一定要传
            total: res.totalCount,
          };
        }}
        search={false}
      />
    </div>
    <div style={{ margin: "10px 0", fontSize: 16, fontWeight: 600 }}>CDK列表({total})
      {
        total ? <TheButton onClick={exportExcel}>Excel导出</TheButton> : null
      }
    </div>
    <ProTable
      actionRef={actionRef_CDK}
      scroll={{ x: "max-content", y: '57vh' }}
      bordered={true}
      options={false}
      columns={columns_CDK}
      pagination={{
        defaultPageSize: 10,
        position: ['bottomCenter'],
        showSizeChanger: false
      }}
      request={async (params) => {
        // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
        // 如果需要转化参数可以在这里进行修改
        const res = await apiGetExchangeInfoPage({
          pageNo: params.current,
          pageSize: params.pageSize,
          exchangeValue: couponId,
          passKeyType: 0
        });
        if (res.code === 0 && res.data) {
          let data = res.data
          setTotal(res.totalCount)
          return {
            data,
            // success 请返回 true，
            // 不然 table 会停止解析数据，即使有数据
            success: res.code === 0,
            // 不传会使用 data 的长度，如果是分页一定要传
            total: res.totalCount,
          };
        }
      }}
      search={false}
    />
  </div>)
}

export default CDKList